package com.myek.springframework.factory.support;

import com.myek.springframework.factory.BeanFactory;
import com.myek.springframework.BeansException;
import com.myek.springframework.factory.config.BeanDefinition;
import com.myek.springframework.factory.support.sigleton.DefaultSingletonBeanRegistry;

/**
 * 继承 DefaultSingletonBeanRegistry 缓存bean,具有单例的能力
 *
 * @author zhangjianbin
 * @date 2021年09月10日17:02
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {

    @Override
    public Object getBean(String name) {
        // 从缓存中获取，有则直接返回
        Object bean = getSingleton(name);
        if (bean != null) {
            System.out.println("查询缓存获取bean");
            return bean;
        }

        // 通过name 获取bean的定义
        BeanDefinition beanDefinition = getBeanDefinition(name);

        // 根据bean定义创建 bean的对象，并缓存bean
        return createBean(name, beanDefinition);
    }

    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition) throws BeansException;
}